package xin.nick.roc.consumer.client;

import io.netty.util.internal.StringUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import xin.nick.roc.consumer.proxy.RpcClientProxy;
import xin.nick.rpc.api.IUserService;
import xin.nick.rpc.pojo.User;

import java.util.List;

/**
 * @author Nick
 * @date 2021/7/4
 * @description
 */
@Component
public class RpcClientStarter implements DisposableBean, CommandLineRunner {


    @Value("${rpc.zk}")
    private String zk;

    @Override
    public void run(String... args) throws Exception {
        // 启动链接zk
        ZkRegister.start(zk);
        // 拿到节点列表
        String path = "/provider";
        List<String> providerList = ZkRegister.getClient().getChildren().forPath(path);

        if (providerList.size() == 0) {
            throw new RuntimeException("没有提供者");
        }
        for(String providerString : providerList) {
            String[] providerInfoArray = providerString.split(":");
            String ip = providerInfoArray[0];
            String port = providerInfoArray[1];

            // 拿到信息之后,创建链接,并存起来
            ProviderInfo.getRpcClientMap().put(providerString, new RpcClient(ip, Integer.valueOf(port)));
        }
    }

    @Override
    public void destroy() throws Exception {
        for (RpcClient rpcClient : ProviderInfo.getRpcClientList()) {
            rpcClient.close();
        }
    }
}
